package com.training.admin.web.controller;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.eclipse.jetty.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.persistence.support.QueryFilter;
import com.demo2do.core.visitor.ObjectVisitor;
import com.training.admin.entity.project.Project;
import com.training.admin.entity.project.ProjectPhase;
import com.training.admin.entity.project.ProjectPhaseCourse;
import com.training.admin.entity.project.ProjectTrainee;
import com.training.admin.entity.project.SurveyQuestion;
import com.training.admin.entity.project.TrainingSurvey;
import com.training.admin.entity.project.TrainingSurveyResult;
import com.training.admin.entity.trainee.Trainee;
import com.training.admin.service.ProjectPhaseCourseService;
import com.training.admin.service.ProjectPhaseService;
import com.training.admin.service.ProjectTraineeService;
import com.training.admin.service.TraineeService;
import com.training.admin.service.TrainingSurveyResultService;
import com.training.admin.service.TrainingSurveyService;

/**
 * 
 * @author Rockett
 * 
 */
@Controller
public class PublicSurveyController {

	private static final Logger logger = LoggerFactory.getLogger(PublicSurveyController.class);

    @Autowired
    private ObjectVisitor objectVisitor;
    
    @Autowired
    private ProjectPhaseService projectPhaseService;
    
    @Autowired
    private ProjectPhaseCourseService projectPhaseCourseService;
    
    @Autowired
    private ProjectTraineeService projectTraineeService;
    
    @Autowired
    private TraineeService traineeService;
    
    @Autowired
    private TrainingSurveyResultService trainingSurveyResultService;
	
    @Autowired
	private TrainingSurveyService trainingSurveyService;

	
	/**
	 * 项目期，输入学员信息
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/survey", method = RequestMethod.GET )
    public ModelAndView surveyByProjectPhase(HttpServletRequest request) {
		
		ModelAndView modelAndView = new ModelAndView("project-result/public-survey-project-phase");
		
		String projectPhaseId = request.getParameter("id");
		
		if (StringUtil.isBlank(projectPhaseId)){
			modelAndView.addObject("noData", true);
			modelAndView.addObject("message", "请求参数错误");
			return modelAndView;
		}
		
		int count = trainingSurveyService.count(TrainingSurvey.class, new QueryFilter().addEquals("projectPhase.id", Long.valueOf(projectPhaseId)));
		if (count<1){
			modelAndView.addObject("noData", true);
			modelAndView.addObject("message", "该期项目评估问卷未生成");
			return modelAndView;

		}
		
		modelAndView.addObject("noData", false);
		modelAndView.addObject("projectPhaseId", projectPhaseId);
		return modelAndView;
	}
	/**
	 * 输入学员信息提交
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/survey-project-phase", method = RequestMethod.POST )
    public ModelAndView surveyByProjectPhaseTrainee(HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("project-result/public-survey");
		
		String projectPhaseId =  request.getParameter("projectPhaseId");
	
		String traineeInput = request.getParameter("trainee");
		
		if (StringUtil.isBlank(projectPhaseId) ||StringUtil.isBlank(traineeInput) ){
		
			modelAndView.addObject("noData", true);
			modelAndView.addObject("message", "请求参数错误");
			return modelAndView;

		}
		
		int count = trainingSurveyService.count(TrainingSurvey.class, new QueryFilter().addEquals("projectPhase.id", Long.valueOf(projectPhaseId)));
		
		if (count<1){
			
			modelAndView.addObject("noData", true);
			modelAndView.addObject("message", "该期项目评估问卷未生成");
			return modelAndView;

		}
		
		List<TrainingSurvey> trainingSurveyList = trainingSurveyService.list( new QueryFilter().addEquals("projectPhase.id", Long.valueOf(projectPhaseId)).addEquals("trainee.email",traineeInput) );
		
		if(trainingSurveyList==null || trainingSurveyList.size()==0|| trainingSurveyList.size()>1){
			
			modelAndView.addObject("noData", true);
			modelAndView.addObject("message", "请求参数错误");
			return modelAndView;
		}
		
		TrainingSurvey trainingSurvey = trainingSurveyList.get(0);
		
		try{
			
			modelAndView = generateSurveyByTrainingSurvey(modelAndView,trainingSurvey);

			
		}catch(Exception exx){
			
			modelAndView.addObject("noData", true);
			modelAndView.addObject("message", "请求参数错误");
			return modelAndView;
		}
		
		
		return modelAndView;
	}
	
    /**
     * 显示问卷
     * @return
     */
	@RequestMapping(value = "/survey-by-id", method = RequestMethod.GET )
    public ModelAndView survey(HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("project-result/public-survey");
		String trainingSurveyIdFromRequest = request.getParameter("id");
		
		try{
			
			Long trainingSurveyId = new Long (trainingSurveyIdFromRequest);
			//load traing survey
			TrainingSurvey trainingSurvey = trainingSurveyService.load(TrainingSurvey.class, trainingSurveyId);
			modelAndView = generateSurveyByTrainingSurvey(modelAndView,trainingSurvey);

		}catch(Exception exx){
			
			modelAndView.addObject("noData", true);
			modelAndView.addObject("message", "请求参数错误");
			return modelAndView;
		}
		modelAndView.addObject("noData", false);
		return modelAndView;   
    }
    
    /**
     * 问卷提交
     * 
     * @return
     */
	@SuppressWarnings("unchecked")
    @RequestMapping(value = "/survey", method = RequestMethod.POST , produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onSurvey(@RequestParam String[] surveyItem,@RequestParam Long projectPhaseId,@RequestParam Long traineeId) {
		HttpResult httpResult = new HttpResult();
        try {
    		
        	//get project Phase 
    		ProjectPhase projectPhase = projectPhaseService.load(ProjectPhase.class,projectPhaseId);
    		
    		//get project phase courses
    		List <ProjectPhaseCourse> projectPhaseCourseList = projectPhaseCourseService.listByProjectPhaseId(projectPhaseId);
    		
    		//get Trainee
    		Trainee trainee =  traineeService.load(Trainee.class, traineeId);
        	
    		//get training survey
        	List<TrainingSurvey> trainingSurveys = trainingSurveyService.list( new QueryFilter().addEquals("projectPhase.id", projectPhaseId).addEquals("trainee.id", traineeId));
        	
        	TrainingSurvey trainingSurvey = new TrainingSurvey();
        	
        		trainingSurvey = trainingSurveys.get(0);
        		
        		if(trainingSurvey.getStatus()!=null && trainingSurvey.getStatus().equals("已提交")){
        			
        			httpResult.fail("500").message("提交问卷失败");
        			logger.error("#onSurvey() - survey submit fail, exception");
        			return httpResult;
        		}

        	
    		
    		List<SurveyQuestion> surveyList = (List<SurveyQuestion>)objectVisitor.evaluate("secure.surveys");
    		List<SurveyQuestion> projectPhaseSurveys = new ArrayList<SurveyQuestion>();
    		List<SurveyQuestion> courseSurveys = new ArrayList<SurveyQuestion>();
			
    		boolean isLastPhase = false;  //是否最后一期
			
			if (projectPhase.getPhase()==projectPhase.getProject().getPhaseCount()){
			
				//最后一期
				isLastPhase = true;
			}
    		
			for(int i=0; i<surveyList.size(); i++){
    			
    			SurveyQuestion surveyQuestion = surveyList.get(i);
				
    			if("phase".equals(surveyQuestion.getLevel())){
					//期评估问卷
					if((isLastPhase && "true".equals(surveyQuestion.getLast())) || (!isLastPhase && !"true".equals(surveyQuestion.getLast()))) {
						
						projectPhaseSurveys.add(surveyQuestion);
					}
				}else{
					courseSurveys.add(surveyQuestion);
				}
    		}    		

    		
    		int index=0;
    		
    		//loop course 
    		for(int ii=0;ii<projectPhaseCourseList.size();ii++){
    			
    			ProjectPhaseCourse projectPhaseCourse = projectPhaseCourseList.get(ii);
    			
    			//loop course questions
	    		for(int i=0;i<courseSurveys.size();i++){
	    			
	    			SurveyQuestion courseSurvey = courseSurveys.get(i);
	    			
	    			if(StringUtil.isBlank(courseSurvey.getCategory()) && StringUtil.isBlank(projectPhaseCourse.getCourse().getType()) || courseSurvey.getCategory().equals(projectPhaseCourse.getCourse().getType()) ){
		    			
	    			    String question = courseSurvey.getQuestion().replace("course_name", projectPhaseCourse.getCourse().getName()).replace("trainer_name", projectPhaseCourse.getTrainer().getName());
	    			    
    				    TrainingSurveyResult trainingSurveyResult = new TrainingSurveyResult(trainee, projectPhase, projectPhaseCourse, question , surveyItem[index],courseSurvey.getLevel(),courseSurvey.getCategory(),courseSurvey.getType(),courseSurvey.getKeywords());
                        trainingSurveyResultService.save(trainingSurveyResult);
                        index++;
	    			}
	    		}
    		}	
    		
    		//loop project phase questions
    		for(int i=0;i<projectPhaseSurveys.size();i++){
    			
    			SurveyQuestion projectPhaseSurvey = projectPhaseSurveys.get(i);
    			TrainingSurveyResult trainingSurveyResult = new TrainingSurveyResult(trainee, projectPhase, projectPhaseSurvey.getQuestion().replace("project_name", projectPhase.getProject().getName()).replace("phase", ""+projectPhase.getPhase()), surveyItem[index],projectPhaseSurvey.getLevel(),projectPhaseSurvey.getCategory(),projectPhaseSurvey.getType(),projectPhaseSurvey.getKeywords());
    			//trainingSurveyResult.setProjectPhaseCourse(projectPhaseCourse);
    			
    			trainingSurveyResultService.save(trainingSurveyResult);
    			
    			index++;
    		}
    		
    		trainingSurvey.setStatus("已提交");
    		if(trainingSurvey.getId()==null){
        		trainingSurveyService.save(trainingSurvey);
    		}else{
        		trainingSurveyService.update(trainingSurvey);
    		}
    		
    		httpResult.success().message("提交问卷成功").data("url", "/survey/success");//成功
        	
		} catch (Exception e) {
    		httpResult.fail("500").message("提交问卷失败");//失败
			logger.error("#onInputResult() - survey fail, exception is [{}]", e);
		}	
        return httpResult;
    }
	
	/**
	 * 
	 * @return
	 */
    @RequestMapping(value = "/survey/success", method = RequestMethod.GET , produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public ModelAndView onSurvySuccess() {
        ModelAndView modelAndView = new ModelAndView("project-result/public-survey-submit");
        modelAndView.addObject("result", true);
        return modelAndView;
    }

	/**
	 * common function to call generate survey
	 * @param trainingSurvey
	 * @return
	 */   
	@SuppressWarnings("unchecked")
    private ModelAndView generateSurveyByTrainingSurvey(ModelAndView modelAndView, TrainingSurvey trainingSurvey) throws Exception{
		
		if (trainingSurvey!=null && trainingSurvey.getId()!=null ){
			
			if(trainingSurvey.getStatus()!=null && trainingSurvey.getStatus().equals("已提交")){
				
				modelAndView.addObject("noData", true);
				modelAndView.addObject("message", "您已完成评估问卷！");
			
				return modelAndView;
			}
			
			//get project Phase
			ProjectPhase projectPhase = trainingSurvey.getProjectPhase();
			if(projectPhase.isDisabled()) {
			    modelAndView.addObject("noData", true);
                modelAndView.addObject("message", "评估问卷数据异常！");
            
                return modelAndView;
			}
			
			Project project = projectPhase.getProject();
			if(project.isDisabled()) {
                modelAndView.addObject("noData", true);
                modelAndView.addObject("message", "评估问卷数据异常！");
            
                return modelAndView;
            }
			
			ProjectTrainee projectTrainee = projectTraineeService.load(project, trainingSurvey.getTrainee());
			if(projectTrainee == null) {
			    modelAndView.addObject("noData", true);
                modelAndView.addObject("message", "评估问卷数据异常！");
            
                return modelAndView;
			}
			
			//get project phase courses
			List <ProjectPhaseCourse> projectPhaseCourseList = projectPhaseCourseService.listByProjectPhaseId(projectPhase.getId());
		
			//get Trainee
			Trainee trainee =  trainingSurvey.getTrainee();
		
			boolean isLastPhase = false;  //是否最后一期
		
			if (projectPhase.getPhase()==projectPhase.getProject().getPhaseCount()){
			
				//最后一期
				isLastPhase = true;
			}
			
			List<SurveyQuestion> surveyList = (List<SurveyQuestion>)objectVisitor.evaluate("secure.surveys");
			List<SurveyQuestion> projectPhaseSurveys = new ArrayList<SurveyQuestion>();
			List<SurveyQuestion> courseSurveys = new ArrayList<SurveyQuestion>();
			
			for(int i=0;i<surveyList.size();i++){
				
				SurveyQuestion surveyQuestion = surveyList.get(i);
				
				if("phase".equals(surveyQuestion.getLevel())){
				
					//期评估问卷
					if((isLastPhase && "true".equals(surveyQuestion.getLast())) || (!isLastPhase && !"true".equals(surveyQuestion.getLast()))) {
						projectPhaseSurveys.add(surveyQuestion);
					}
				}else{
				
					courseSurveys.add(surveyQuestion);
				}
			}
		
			modelAndView.addObject("projectPhase", projectPhase);
			modelAndView.addObject("projectPhaseCourses", projectPhaseCourseList);
			modelAndView.addObject("trainee", trainee);
			modelAndView.addObject("projectPhaseSurveys", projectPhaseSurveys);
			modelAndView.addObject("courseSurveys", courseSurveys);
	
		}else{
			
			modelAndView.addObject("noData", true);
			modelAndView.addObject("message", "请求参数错误");
		}
	
		modelAndView.addObject("noData", false);
		return modelAndView;
	}
	
	
    
}
